import cv2
import os
import re
import shutil
from road_class import RoadClass

def images_to_show(image_folder, output, sort_by='filename'):
    """
    将图像文件夹转换为视频
    :param image_folder: 图片文件夹路径
    :param output_video: 输出视频路径（需包含扩展名，如.mp4）
    :param fps: 帧率（每秒帧数）
    :param sort_by: 排序方式 ('filename' 按文件名 | 'date' 按修改时间)
    """

    rc = RoadClass()
    box_x, box_y = 420, 0
    box_width, box_height = 1080, 1080
    start_y = 20
    line_h = 18
    resize_x = 4

    # 获取所有图像文件
    images = [img for img in os.listdir(image_folder) 
              if img.endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
    
    # 按文件名或修改时间排序
    if sort_by == 'filename':
        images.sort(key=lambda x: [int(c) if c.isdigit() else c for c in re.split('(\d+)', x)])
    elif sort_by == 'date':
        images.sort(key=lambda x: os.path.getmtime(os.path.join(image_folder, x)))
    
    if not images:
        raise ValueError("未找到支持的图像文件（.png, .jpg, .jpeg, .bmp）")
    
    # 获取第一张图像的分辨率
    frame = cv2.imread(os.path.join(image_folder, images[0]))
    height, width, _ = frame.shape
    resize_shape = (int(width / resize_x), int(height / resize_x))
  
       
    # 写入所有图像帧
    idd = 0
    for image in images:
        img_path = os.path.join(image_folder, image)
        frame = cv2.imread(img_path)
        if frame is not None:
        
            results, info = rc.infer(frame)

            cv2.rectangle(frame, (box_x, box_y), 
                (box_x + box_width, box_y + box_height), 
                (0, 255, 0), 2)
            
            frame = cv2.resize(frame, resize_shape)


            infos = info.split('\n')[:4]
            window1 = f"window1: {infos[1].split(', maxlen')[0].replace('windows: [deque(', '')}"
            window2 = f"window2: {infos[1].split('deque(')[-1].replace(', maxlen=10)]', '')}"
            infos_ = [image, infos[0], window1, window2, infos[2], infos[3]]
           
            for i, line in enumerate(infos_):
                y = start_y + i*line_h
                cv2.putText(frame, line, (10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 0), 1, cv2.LINE_AA)

            cv2.imwrite(f"{output}/{image}", frame)
            print(f"已添加: {image}")
        else:
            print(f"警告: 无法读取图像 {img_path}")
        
        idd += 1
        if idd == -1:
            break
    

    print(f"保存至: {output}")

# 使用示例
if __name__ == "__main__":
    image_folder = "/home/nzd/save_imgs"  # 替换为你的图片文件夹路径
    output = "../save_show_imgs/"     # 输出视频文件名
    
    if not os.path.exists(output):
       os.makedirs(output)

    images_to_show(
        image_folder=image_folder,
        output=output,
        sort_by='filename'  # 可选 'filename' 或 'date'
    )